import Taro, { Component, Config } from '@tarojs/taro'
import { connect } from '@tarojs/redux'
import { setHotelDate, setHotelCity } from '../../../actions/hotel'
import { View } from '@tarojs/components'
import { AtIndexes } from 'taro-ui'
import { _apiGetCityList } from '../../../service/api'
import './index.styl'

const HOTEL_CITY_CATCH_KEY = 'LINE_SEARCH_HISTORY_LIST'
const HOTEL_CITY_CATCH_LENGTH = 10

interface PageState {
  historyList: string[],
  hotList: any[],
  cityList: any[],
  isLoadData: boolean
}
interface PageDispatchProps {
  setHotelDate: (checkInDate: string, checkOutDate: string) => void
  setHotelCity: (city: string) => void
}
type PageOwnProps = {
  hotel: any
}

interface HotelCanlendar {
  props: PageState & PageDispatchProps & PageOwnProps
}

@connect(({ hotel }) => ({
  hotel: {
    checkInDate: hotel.checkInDate,
    checkOutDate: hotel.checkOutDate,
    city: hotel.city
  }
}), dispatch => ({
  setHotelDate (checkInDate, checkOutDate) {
    dispatch(setHotelDate(checkInDate, checkOutDate))
  },
  setHotelCity(city) {
    dispatch(setHotelCity(city))
  }
}))

class HotelCanlendar extends Component {
  constructor() {
    super(...arguments)
  }
  state: PageState = {
    historyList: [],
    hotList: [],
    cityList: [],
    isLoadData: false
  }
  config: Config = {
    navigationBarTitleText: '选择城市'
  }
  componentDidMount() {
    let catchedCityList = Taro.getStorageSync(HOTEL_CITY_CATCH_KEY) || []
    
    this.setState({ historyList: catchedCityList })
    this._initFn()
  }
  selectCity(data) { // 选择城市
    let setCityName: string = ''

    if (typeof data === 'string') {
      setCityName = data
    } else if (typeof data === 'object') {
      setCityName = data.name
    }

    this.props.setHotelCity(setCityName)
    this._catchHotelCity(setCityName)
    Taro.navigateBack()
  }
  async _initFn() {
    const params = {
      country_name: '中国',
      level: 1
    }
    let setCityList: any[] = []
    const { data: { flag, data } } = await _apiGetCityList(params)
    
    if (flag !== 0) return

    data.city_list.length && data.city_list.forEach(itm => {
      const itmKey = itm.py.substr(0, 1).toUpperCase()
      const findIndex = setCityList.findIndex(i => i.key === itmKey)
      
      findIndex >= 0
        ? setCityList[findIndex].items.push({ name: itm.city_name })
        : setCityList.push({
            title: itmKey,
            key: itmKey,
            items: [ { name: itm.city_name } ]
          })
    })

    this.setState({ hotList: data.hot_city_list, cityList: setCityList, isLoadData: true })
  }
  _catchHotelCity(val) {
    let setHotelCityList = Taro.getStorageSync(HOTEL_CITY_CATCH_KEY) || []
    const len = setHotelCityList.length
    const findIndex = setHotelCityList.findIndex(i => i === val)

    if (findIndex >= 0) {
      setHotelCityList.splice(findIndex, 1)
      setHotelCityList = [val, ...setHotelCityList]
    } else {
      len >= HOTEL_CITY_CATCH_LENGTH && setHotelCityList.splice(len - 1, 1)
      setHotelCityList = [val, ...setHotelCityList]
    }

    Taro.setStorageSync(HOTEL_CITY_CATCH_KEY, setHotelCityList)
  }
  render() {
    return (
      <View className='bg'>
        {
          this.state.isLoadData &&
          <View className='city-list'>
            {
              this.state.cityList.length &&
              <AtIndexes list={this.state.cityList} topKey='顶' onClick={this.selectCity.bind(this)}>
                <View className='group-box'>
                  <View className='group'>
                    <View className='title'>历史城市</View>
                    <View className='city-wrapper'>
                      <View className='city-box'>
                        {
                          this.state.historyList.map((itm, ind) => (
                            <View
                            key={ind}
                            className='city'
                            hoverClass='city-hover'
                            onClick={this.selectCity.bind(this, itm)}>{itm}</View>
                          ))
                        }
                      </View>
                    </View>
                  </View>
                  <View className='group'>
                    <View className='title'>热门城市</View>
                    <View className='city-wrapper'>
                      <View className='city-box'>
                        {
                          this.state.hotList.map((itm, ind) => 
                          <View
                            key={ind}
                            className='city'
                            onClick={this.selectCity.bind(this, itm.city_name)}
                            hoverClass='city-hover'>{itm.city_name}</View>)
                        }
                      </View>
                    </View>
                  </View>
                </View>
              </AtIndexes>
            }
          </View>
        }
        {
          !this.state.isLoadData &&
            <View className='load-before'>
              {
                [1, 2, 4, 5, 6, 7, 8, 9, 10,
                11, 12, 13, 14, 15, 16, 17,
                18, 19, 10].map((_, ind) => <View key={ind}></View>)
              }
            </View>
        }
      </View>
    )
  }
}
export default HotelCanlendar